<template>
  <el-card class="box-card">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="基本信息" name="basic">
        <el-row :gutter="20">
          <el-col :xs="24" :span="10">
            <el-form
              ref="form"
              :rules="rules"
              :model="formData"
              label-width="60px"
              style="max-width: 660px"
              :label-position="'top'"
            >
              <el-form-item prop="avatar" label="头像">
                <dt-uploadAvatar
                  ref="dtUploadAvatarRef"
                  @success-upload="handleCropperSuccess"
                />
              </el-form-item>
              <el-form-item label="账号" prop="account">
                <el-input
                  v-model="formData.account"
                  autocomplete="off"
                  disabled
                />
              </el-form-item>
              <el-form-item label="姓名" prop="realName">
                <el-input
                  v-model="formData.realName"
                  maxlength="20"
                  show-word-limit
                  autocomplete="off"
                  class="limit"
                />
              </el-form-item>
              <el-form-item label="昵称" prop="nickName">
                <el-input
                  v-model="formData.nickName"
                  maxlength="20"
                  show-word-limit
                  autocomplete="off"
                  class="limit"
                />
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="formData.sex">
                  <el-radio label="M">男</el-radio>
                  <el-radio label="F">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="生日" prop="birthday">
                <el-date-picker
                  v-model="formData.birthday"
                  style="width: 100%"
                  type="date"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input
                  v-model="formData.email"
                  autocomplete="off"
                  maxlength="50"
                  class="limit"
                />
              </el-form-item>

              <el-form-item label="电话" prop="phone">
                <el-input
                  v-model="formData.phone"
                  autocomplete="off"
                  maxlength="11"
                  class="limit"
                />
              </el-form-item>
              <el-form-item style="margin-top:40px">
                <el-button
                  type="primary"
                  size="mini"
                  @click="onSubmit('form')"
                >保存</el-button>
                <el-button
                  size="mini"
                  @click="onCancel('form')"
                >取消</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="2" :xs="24">
            <el-divider direction="vertical" />
          </el-col>
          <el-col :span="10" :xs="24">
            <el-form
              :model="formData"
              label-width="60px"
              style="max-width: 660px"
              :label-position="'top'"
            >
              <el-form-item label="已绑定密保邮箱" prop="email">
                <el-input
                  v-model="email"
                  autocomplete="off"
                  maxlength="50"
                  class="limit"
                  disabled
                />
              </el-form-item>
              <el-form-item label="已绑定密保手机" prop="phone">
                <el-input
                  v-model="phone"
                  autocomplete="off"
                  maxlength="50"
                  class="limit"
                  disabled
                />
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="修改密码" name="updatePw">
        <DtUpdatePw ref="updatePw" @cancel="cancel" />
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>
<script>
import { encryption } from 'DQBasic-vue-component'
import api from '@/framework/api/userCenter/resource'
import { default as request, cloud } from '@/framework/utils/request'
import store from '@/store'
import DtUpdatePw from '../dt-updatePw/index.vue'
import { checkPhoneOrEmailOnly } from '@/framework/api/userCenter/sysUser'
import { checkPhone, checkEmail, checkAccountName } from '@/framework/utils/validate'

export default {
  name: 'DtPersonalCenter',
  components: { DtUpdatePw },
  props: {
    // activeName: {
    //   type: String,
    //   default: 'basic'
    // }
  },

  data() {
    const validatePhone = async (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号/电话'))
      } else if (!checkPhone(value)) {
        callback(new Error('请输入合法的手机号/电话'))
      } else if (!(await this.checkOnly(rule, value))) {
        callback(new Error('电话已存在'))
      } else {
        callback()
      }
    }
    // 邮箱校验
    const validateEmail = async (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入邮箱'))
      } else if (!checkEmail(value)) {
        callback(new Error('邮箱格式错误'))
      } else if (!(await this.checkOnly(rule, value))) {
        callback(new Error('邮箱已存在'))
      } else callback()
    }
    // 姓名校验
    const validateRealName = async (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入姓名'))
      } else if (!checkAccountName(value)) {
        callback(new Error('请输入汉字、字母或数字'))
      } else callback()
    }
    return {
      activeName: 'basic',
      imgFileId: '',
      formData: {},
      realName: '',
      account: '',
      email: '',
      phone: '',
      avatarSrc: '',
      url:
        `${process.env.VUE_APP_BASE_API +
        cloud.file
        }/sysFileInfo/upload?secretFlag=N&token=${
          store.getters.token}`,
      rules: {
        avatar: [{ required: true, message: '请上传头像', trigger: 'blur' }],
        account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        realName: [{ required: true, validator: validateRealName, trigger: 'blur' }],
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        email: [
          { required: true, trigger: 'blur', validator: validateEmail }
        ]
      }
    }
  },
  methods: {
    async checkOnly(rule, value) {
      const form = {}
      form[rule.field] = value
      form.userId = this.formData.userId
      const temp = encryption({
        data: form
      })
      const { message } = await checkPhoneOrEmailOnly(temp)
      if (message == '') {
        return true
      } else {
        return false
      }
    },
    infoUserData() {
      request({
        url: `${cloud.usercenter}/sysUser/currentUserInfo`,
        method: 'get'
      }).then((res) => {
        this.formData = res.data
        this.cancelData = res.data
        this.avatarSrc =
          `${process.env.VUE_APP_BASE_API +
          cloud.file
          }/sysFileInfo/private/preview?fileId=${
            res.data.avatar
          }&token=${
            store.getters.token}`
        this.$refs.dtUploadAvatarRef.resultImg =
          `${process.env.VUE_APP_BASE_API +
          cloud.file
          }/sysFileInfo/private/preview?fileId=${
            res.data.avatar
          }&token=${
            store.getters.token}`
        this.formData.avatar = res.data.avatar
        this.realName = this.formData.realName
        this.account = this.formData.account
        this.email = this.formData.email
        this.phone = this.formData.phone
      })
    },
    handleClick(tab, event) {
      if (tab.name == 'updatePw') {
        this.$refs.updatePw.getPwdRole()
      }
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submit()
        } else {
          return false
        }
      })
    },
    submit() {
      api.updateAvatar(this.formData.avatar).then((res) => {
        store.dispatch('user/getInfo')
      })
      // this.formData.avatar = this.imgFileId
      const temp = encryption({
        data: this.formData
      })
      request({
        url: `${cloud.usercenter}/sysUser/updateInfo`,
        method: 'post',
        data: temp,
        headers: {
          'Content-Type': 'application/json;charset=UTF-8'
        }
      }).then((res) => {
        if (res.code === '00000') {
          this.$message({
            type: 'success',
            message: '修改成功'
          })
          const dom = document.getElementById('username')
          dom.innerText = this.formData.realName
          this.realName = this.formData.realName
          this.account = this.formData.account
          this.email = this.formData.email
          this.phone = this.formData.phone
          store.dispatch('user/getInfo')
        } else {
          this.$message({
            type: 'error',
            message: '修改失败'
          })
        }
      })
    },
    onCancel() {
      this.$refs.form.clearValidate()
      this.infoUserData()
      this.$emit('cancel', false)
    },
    cancel() {
      this.$emit('cancel', false)
    },
    handleCropperSuccess(file) {
      this.formData.avatar = file.fileId
      this.$message({
        type: 'success',
        message: '上传成功'
      })
    }
  }
}
</script>
<style scoped>
.el-divider {
  width: 0px;
  height: 612px;
  opacity: 1;
  border: 1px solid #ebeef5;
  margin: 0;
}
p {
  word-break: break-all;
}
.el-col-2 {
  width: 0;
}
::v-deep .el-tabs__header {
  margin-left: 4px;
  margin-bottom: 16px;
}
::v-deep .el-tabs__content {
  margin-left: 20px;
}
::v-deep .el-form-item{
  margin-bottom: 24px;
}
::v-deep .el-form-item__content{
  margin-top: 8px;
}
::v-deep .el-avatar--circle{
  width: 40px !important;
  height: 40px !important;
  line-height: 40px !important;
}
::v-deep .el-form--label-top .el-form-item__label{
  padding: 0;
}
::v-deep .el-row .el-col {
 padding-right: 0 !important;
}
::v-deep .el-row .el-col:nth-child(3) {
  margin-top: 24px !important;
  margin-left: 40px !important;
}
span {
  font-size: 14px;
  font-family: HarmonyOS Sans SC-Regular, HarmonyOS Sans SC;
  line-height: 24px;
}
::v-deep .el-tabs__item{
  padding: 0 32px;
  line-height: 22px;
  height: 22px;
  margin-bottom: 24px;
  margin-top: 4px;
  font-size: 16px;
}
.account{
  margin-left: 12px;
  margin-top: 10px;
  font-size: 14px;
  font-weight: 500;
  line-height: 20px;
}
</style>
